"""Plot estimated carbon credit income per hectare and save as PNG.

This script uses a non-interactive matplotlib backend so it runs in
headless environments. It always writes `file_plot.png` next to the
script and will attempt to show the plot if a GUI backend is available.
"""
import os
import sys
import matplotlib

# Use a non-interactive backend by default so the script does not fail
# when no display is available. The environment variable MPLBACKEND can
# override this if needed.
matplotlib.use(os.environ.get('MPLBACKEND', 'Agg'))
import matplotlib.pyplot as plt


def main():
	countries = ['India', 'Bangladesh', 'Nepal', 'Sri Lanka', 'Pakistan']
	income_per_ha = [85, 60, 50, 70, 55]

	fig, ax = plt.subplots(figsize=(8, 4.5))
	ax.plot(countries, income_per_ha, marker='o', linestyle='-', color='darkgreen')
	ax.set_title('Estimated Carbon Credit Income per Hectare (USD/year)')
	ax.set_ylabel('USD per Hectare')
	ax.grid(True, linestyle='--', alpha=0.6)

	# Save next to the script
	try:
		out_dir = os.path.dirname(os.path.abspath(__file__))
	except NameError:
		out_dir = os.getcwd()
	out_path = os.path.join(out_dir, 'file_plot.png')
	fig.tight_layout()
	fig.savefig(out_path, dpi=150)
	print(f"Saved plot to: {out_path}")

	# Try to show the figure but don't raise on headless backends
	try:
		plt.show()
	except Exception:
		pass


if __name__ == '__main__':
	try:
		main()
		sys.exit(0)
	except Exception as exc:
		print(f"file.py failed: {exc}")
		sys.exit(1)
